package com.yijiu.trb;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yijiu.action.BaseAction;
import com.yijiu.adapter.ViewPagerAdapter;
import com.yijiu.network.Request;
import com.yijiu.resource.ActionType;
import com.yijiu.resource.C;
import com.yijiu.resource.CacheData;
import com.yijiu.response.RequestAccountInfoResponse;
import com.yijiu.response.RequestPersonalInfoResponse;
import com.yijiu.utils.ConvertUtils;
import com.yijiu.view.FixedSpeedScroller;

/**
 * 带有用户信息的activity
 * 
 * @author TangChao
 */
public class BTitleWithUserinfoActivity extends BNotitleActivity
{
	private LinearLayout screenView;

	/**
	 * 标题栏姓名
	 */
	private TextView nameTextView;

	/**
	 * 标题栏余额
	 */
	private TextView moneyTextView;

	/**
	 * 标题栏认证状态
	 */
	private TextView statusTextView;

	private RelativeLayout.LayoutParams relativeLp;

	// 底部小点图片
	private ImageView[] pointsArray;

	// 记录当前选中位置
	private int currentIndex;

	private ViewPager vpAdPics;

	private int i = 0;

	private boolean is = true;

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			try
			{
				Field field = ViewPager.class.getDeclaredField("mScroller");
				field.setAccessible(true);
				FixedSpeedScroller scroller = new FixedSpeedScroller(vpAdPics.getContext(), new AccelerateInterpolator());
				field.set(vpAdPics, scroller);
				scroller.setmDuration(2000);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			vpAdPics.setCurrentItem(msg.arg1);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		relativeLp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	}

	public void refresh()
	{
		requestAccountInfo(CacheData.APP_KEY);
	}

	/**
	 * 账户信息请求
	 * 
	 * @param appKey
	 */
	private void requestAccountInfo(String appKey)
	{
		String inputStr = "service=queryAcountInfo";
		encryptBase(inputStr, C.PRIVATE_KEY);
		BaseAction action = new BaseAction(encodedData, encriptData, appKey);
		RequestAccountInfoResponse requestAccountInfoResponse = new RequestAccountInfoResponse();
		Request request = new Request(action, requestAccountInfoResponse, ActionType.REQUEST_ACCOUNT_INFO);
		netManager.excute(request, this, this);
		showProgress("正在获取数据");
	}

	/**
	 * 个人信息请求
	 * 
	 * @param appKey
	 */
	private void requestPersonInfo(String appKey)
	{
		String inputStr = "service=personalInfoService";
		encryptBase(inputStr, C.PRIVATE_KEY);
		BaseAction action = new BaseAction(encodedData, encriptData, appKey);
		RequestPersonalInfoResponse requestPersonalInfo = new RequestPersonalInfoResponse();
		Request request = new Request(action, requestPersonalInfo, ActionType.REQUEST_PERSONAL_INFO);
		netManager.excute(request, this, this);
		showProgress("正在获取数据");
	}

	/**
	 * 请求成功
	 */
	@Override
	public void getResult(Request r)
	{
		super.getResult(r);
		switch (r.getType())
		{
			case ActionType.REQUEST_ACCOUNT_INFO:// 请求账户信息
				RequestAccountInfoResponse itemAccountInfoResponse = (RequestAccountInfoResponse) r.getResponse();
				CacheData.AVAILABLE_BALANCE = itemAccountInfoResponse.field.availableBalance + "";
				requestPersonInfo(CacheData.APP_KEY);
				break;
			case ActionType.REQUEST_PERSONAL_INFO:// 请求个人信息
				RequestPersonalInfoResponse itemPersonalInfoResponse = (RequestPersonalInfoResponse) r.getResponse();
				CacheData.BANK_CARD_NAME = itemPersonalInfoResponse.field.bankName;
				CacheData.BANK_CARD_NUMBER = itemPersonalInfoResponse.field.bankCardNo;
				CacheData.REAL_NAME_STATUS = itemPersonalInfoResponse.field.realNameStatus;
				CacheData.BANK_ICON_URL = itemPersonalInfoResponse.field.banklog;
				CacheData.MOBILE_NUMBER = itemPersonalInfoResponse.field.mobile;
				showPersonalInfo(itemPersonalInfoResponse.field.realName,
						(CacheData.AVAILABLE_BALANCE == null || "null".equals(CacheData.AVAILABLE_BALANCE) ? "0.0"
								: CacheData.AVAILABLE_BALANCE));
				break;
			default:
				break;
		}
	}

	/**
	 * 请求失败
	 */
	@Override
	public void notifyError(int type, int errorCode, String errorMsg)
	{
		super.notifyError(type, errorCode, errorMsg);
		switch (type)
		{
			case ActionType.REQUEST_ACCOUNT_INFO:
			case ActionType.REQUEST_PERSONAL_INFO:
				break;
			default:
				break;
		}
	}

	/**
	 * 重新请求
	 */
	@Override
	public void rePost(Request r)
	{
		super.rePost(r);
	}

	public void setTitleInfoVisibility()
	{
		if (CacheData.LOGIN_STATUS)
		{
			nameTextView.setVisibility(View.VISIBLE);
			moneyTextView.setVisibility(View.VISIBLE);
			statusTextView.setVisibility(View.VISIBLE);
		}
	}

	public void setTitleInfoInVisibility()
	{
		try
		{
			nameTextView.setVisibility(View.GONE);
			moneyTextView.setVisibility(View.GONE);
			statusTextView.setVisibility(View.VISIBLE);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void setContentView(int layoutResID)
	{
		LinearLayout screenLayout = getScreenView();
		RelativeLayout contentLayout = (RelativeLayout) screenLayout.findViewById(R.id.content_view);
		View contentView = inflater.inflate(layoutResID, null);
		contentLayout.addView(contentView, relativeLp);
		super.setContentView(screenLayout);
	}

	@Override
	public void setContentView(View contentView)
	{
		LinearLayout screenLayout = getScreenView();
		RelativeLayout contentLayout = (RelativeLayout) screenLayout.findViewById(R.id.content_view);
		contentLayout.addView(contentView, relativeLp);
		super.setContentView(screenLayout);
	}

	@Override
	public void setContentView(View contentView, LayoutParams params)
	{
		if (!(params instanceof RelativeLayout.LayoutParams))
		{
			throw new RuntimeException("You must put the RelativeParams");
		}
		LinearLayout screenLayout = getScreenView();
		RelativeLayout contentLayout = (RelativeLayout) screenLayout.findViewById(R.id.content_view);
		contentLayout.addView(contentView, params);
		super.setContentView(screenLayout);
	}

	private LinearLayout getScreenView()
	{
		if (CacheData.LOGIN_STATUS)
		{
			try
			{
				screenView = (LinearLayout) inflater.inflate(R.layout.with_userinfo_screen_layout, null);
				nameTextView = (TextView) screenView.findViewById(R.id.tv_my_account_name);
				moneyTextView = (TextView) screenView.findViewById(R.id.tv_my_account_money);
				statusTextView = (TextView) screenView.findViewById(R.id.tv_my_account_status);
				moneyTextView.setText("账户余额： "
						+ (CacheData.AVAILABLE_BALANCE == null || "null".equals(CacheData.AVAILABLE_BALANCE) ? "0.0"
								: CacheData.AVAILABLE_BALANCE) + "元");
				nameTextView.setText(CacheData.REAL_NAME);
				if (CacheData.REAL_NAME_STATUS.equals("IS"))// 已认证
				{
					statusTextView.setText("(已认证)");
				}
				else if (CacheData.REAL_NAME_STATUS.equals("IN"))// 认证中
				{
					statusTextView.setText("(认证中)");
				}
				else if (CacheData.REAL_NAME_STATUS.equals("N"))// 未认证
				{
					statusTextView.setText("(未认证)");
				}
				else if (CacheData.REAL_NAME_STATUS.equals("NO"))// 认证未通过
				{
					statusTextView.setText("(认证未通过)");
				}
				else if (CacheData.REAL_NAME_STATUS.equals(""))// 未取到值
				{
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			screenView = (LinearLayout) inflater.inflate(R.layout.with_unlogin_userinfo_screen_layout, null);
			findViewsInit(screenView);
		}
		return screenView;
	}

	private void findViewsInit(LinearLayout screenView)
	{
		vpAdPics = (ViewPager) screenView.findViewById(R.id.vp_home_ad);
		List<View> viewAdList = new ArrayList<View>();
		for (int i = 0; i < 3; i++)
		{
			View viewAd = LayoutInflater.from(this).inflate(R.layout.view_ad_layout, null);
			ImageView adPic = (ImageView) viewAd.findViewById(R.id.iv_ad_pic);
			adPic.setBackgroundResource(R.drawable.ad_pic);
			viewAdList.add(viewAd);
		}
		ViewPagerAdapter vpAdAdapter = new ViewPagerAdapter(viewAdList);
		vpAdPics.setAdapter(vpAdAdapter);
		initPoints(screenView);
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while (is)
				{
					try
					{
						Message ms = handler.obtainMessage();
						ms.arg1 = i;
						handler.sendMessage(ms);
						Thread.sleep(5000);
						i++;
						if (i > 2)
						{
							i = 0;
						}
					}
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				}
			}
		}).start();
		vpAdPics.setOnPageChangeListener(new OnPageChangeListener()
		{
			@Override
			public void onPageSelected(int arg0)
			{
				setCurPoint(arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2)
			{
			}

			@Override
			public void onPageScrollStateChanged(int arg0)
			{
			}
		});
	}

	/**
	 * 显示标题栏上面的姓名、账户余额
	 */
	public void showPersonalInfo(String nameStr, String balanceStr)
	{
		try
		{
			nameTextView.setText(nameStr);
			moneyTextView.setText("账户余额：" + balanceStr + "元");
			if (CacheData.REAL_NAME_STATUS.equals("IS"))// 已认证
			{
				statusTextView.setText("(已认证)");
			}
			else if (CacheData.REAL_NAME_STATUS.equals("IN"))// 认证中
			{
				statusTextView.setText("(认证中)");
			}
			else if (CacheData.REAL_NAME_STATUS.equals("N"))// 未认证
			{
				statusTextView.setText("(未认证)");
			}
			else if (CacheData.REAL_NAME_STATUS.equals("NO"))// 认证未通过
			{
				statusTextView.setText("(认证未通过)");
			}
			else if (CacheData.REAL_NAME_STATUS.equals(""))// 未取到值
			{
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void initPoints(LinearLayout screenView)
	{
		LinearLayout llayoutGuidePoints = (LinearLayout) screenView.findViewById(R.id.llayout_ad_points);
		LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		int padding = ConvertUtils.dip2px(this, 5);
		for (int i = 0; i < 3; i++)
		{
			ImageView iv = new ImageView(this);
			iv.setPadding(padding, padding, padding, padding);
			iv.setLayoutParams(lp);
			iv.setImageResource(R.drawable.ad_points);
			llayoutGuidePoints.addView(iv);
		}
		pointsArray = new ImageView[3];
		// 循环取得小点图片
		for (int i = 0; i < 3; i++)
		{
			pointsArray[i] = (ImageView) llayoutGuidePoints.getChildAt(i);
			pointsArray[i].setEnabled(true);// 都设为灰色
			pointsArray[i].setTag(i);// 设置位置tag，方便取出与当前位置对应
		}
		currentIndex = 0;
		pointsArray[currentIndex].setEnabled(false);// 设置为白色，即选中状态
	}

	/**
	 * 这只当前引导小点的选中
	 */
	private void setCurPoint(int positon)
	{
		if (positon < 0 || positon > 3 - 1 || currentIndex == positon)
		{
			return;
		}
		pointsArray[positon].setEnabled(false);
		pointsArray[currentIndex].setEnabled(true);
		currentIndex = positon;
	}

	public void userScreenClick(View v)
	{
		int id = v.getId();
		switch (id)
		{
			case R.id.btn_unlogin_btn:
				initIntent(this, LoginActivity.class);
				break;
			case R.id.btn_my_account_in:
				initIntent(this, CutIn.class);
				break;
			case R.id.btn_my_account_out:
				initIntent(this, LineOut.class);
				break;
			default:
				break;
		}
	}
}
